const path = require("node:path");
const fs = require("node:fs");
const { exec_shell } = require("./shell_tool");
const { get_fst_file } = require("./file_tool");
const { warn } = require("./log_tool");
async function which(target) {
    let cmd;
    switch (process.platform) {
        case "win32": {
            cmd = "where";
            break;
        }
        default: {
            cmd = "which";
            break;
        }
    }

    let file;
    const stdout = await exec_shell({
        cmd: `${cmd} ${target}`,
        capture_stdout: true,
        ignore_code: true,
        quiet: true,
    });
    if (stdout) {
        /** @type {string[]} */
        let files = stdout.split(/[\r\n]{1,2}/);
        files = files.filter((v) => v?.trim());
        // windows系统下，优先选择有 .cmd 或者 .exe
        if (process.platform === "win32") {
            const preferExts = [".exe", ".cmd"];
            files.sort((a, b) => {
                const exta = path.extname(a);
                const extb = path.extname(b);
                if (preferExts.includes(exta)) {
                    return -1;
                } else if (preferExts.includes(extb)) {
                    return 1;
                }
                return 0;
            });
        }
        file = get_fst_file(files);
        if (file) {
            file = fs.realpathSync(file);
        }
    }
    return file;
}

module.exports = {
    which,
};
